//
//  KillListViewController.m
//  何五路
//
//  Created by _ADY on 15/7/6.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "KillListViewController.h"
#import "GoodsDetailsViewController.h"
@interface KillListViewController ()

@end
#define geHight 50
#define getableH screenMySize.size.height/4
@implementation KillListViewController
@synthesize killArray,allArray;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;

}

- (void)viewWillAppear:(BOOL)animated
{
    self.view.backgroundColor = bgColor;
    self.title = @"掌上秒杀";
    selectInt = 0;
    if (allArray != nil) {
        [allArray  removeAllObjects];
        allArray = nil;
    }
    allArray = [[NSMutableDictionary alloc] initWithCapacity:10];
    [super viewWillAppear:animated];
    [self gotoAction];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    
    int page =scrollView.bounds.origin.x/self.view.bounds.size.width;
   
    selectInt = page;
    [mSidebar sSelectedSegmentIndex:page];
    [self gotoAction];

}

- (void)MySidebar:(int)aType
{
//    NSLog(@"MySidebar %d",aType);
    selectInt = aType;

    [taScrollView scrollRectToVisible:CGRectMake(self.view.bounds.size.width*selectInt,geHight+64, self.view.bounds.size.width, self.view.bounds.size.height - geHight-64) animated:YES];
    [self gotoAction];
    
}

-(void)setTime
{
    
}

-(void)gotoAction
{
    if (killArray != nil) {
        [killArray removeAllObjects];
        killArray = nil;
    }
    killArray = [[NSMutableArray alloc] init];
    
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:@"AppHomeActPanicBuy" forKey:@"code"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *myArray = [SendService HomepageSecKill:postDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            for (NSDictionary *pic in [myArray objectForKey:@"Entity"])
            {
                [killArray addObject:pic];
            }
            if (killArray.count == 0) {
                return;
            }
            NSMutableArray* set = [[NSMutableArray alloc] initWithCapacity:0];
            NSMutableArray* set1 = [[NSMutableArray alloc] initWithCapacity:0];
            for (NSDictionary *dic in killArray)
            {
                [set addObject:[dic objectForKey:@"CodeName"]];
                [set1 addObject:@""];
                
            }
            NSArray *array = set;
            NSArray *array1 = set1;
            if (mSidebar == nil)
            {
                mSidebar = [[MySidebar alloc] initWithFrame:CGRectMake(0, 64, screenMySize.size.width, geHight)];
                mSidebar.delegate = self;
                mSidebar.selectedIndex = -1;
                 [mSidebar setTitle:array setImage:array1  setSeclet:array1 setBOOL:YES];
                [self.view addSubview:mSidebar];
            }
            else
                [mSidebar setTitle:array setImage:array1  setSeclet:array1 setBOOL:NO];
            [mSidebar sSelectedSegmentIndex:selectInt];
            
            
            if (taScrollView == nil)
            {
                taScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,geHight+64, self.view.bounds.size.width, self.view.bounds.size.height - geHight-64)];
                taScrollView.backgroundColor = [UIColor whiteColor];
                [taScrollView setDelegate:self];
                [taScrollView setPagingEnabled:YES];
                [taScrollView setShowsHorizontalScrollIndicator:NO];
                [self.view addSubview:taScrollView];
                
                for (int i = 0; i < killArray.count; i ++)
                {
                    UITableView *mTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width*i,20, self.view.bounds.size.width, self.view.bounds.size.height-geHight-20-64)];
                    mTableView.delegate = self;
                    mTableView.dataSource = self;
                    mTableView.tag = 100+i;
                    mTableView.backgroundColor = [UIColor clearColor];
                    [taScrollView addSubview:mTableView];
                    
                    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
                    [mTableView setTableFooterView:v];
                }
            }
            [self labelview];
            
            [taScrollView setContentSize:CGSizeMake(self.view.bounds.size.width*killArray.count,self.view.bounds.size.height-geHight-64)];

            NSMutableDictionary *postDic4 = [[NSMutableDictionary alloc] init];
            [postDic4 setObject:[[killArray objectAtIndex:selectInt] objectForKey:@"Code"] forKey:@"code"];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSDictionary *myArray = [SendService GetSecKillProductListByPlay:postDic4];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                     if (![[NSString stringWithFormat:@"%@",[myArray objectForKey:@"Result"]] isEqualToString:@"error"])
                     {
                         [allArray setValue:[myArray objectForKey:@"Entity"] forKey:[NSString stringWithFormat:@"%d",selectInt]];
                         
                         NSLog(@"场次秒杀商品列表 %@",myArray);
                         UITableView *mTableView = (UITableView*)[self.view viewWithTag:100+selectInt];
                         [mTableView reloadData];
                     }
                    else
                    {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[myArray objectForKey:@"Message"]  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        [alert show];
                    }

                });
            });
            
        });
    });
    
 

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self popself];
}

-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)labelview
{
    if (labelView != nil) {
        [labelView removeFromSuperview];
        labelView = nil;
    }
    labelView = [[UIView alloc]  initWithFrame:CGRectMake(self.view.bounds.size.width*selectInt, 0, self.view.bounds.size.width, 20)];
    [taScrollView addSubview:labelView];
    
    UILabel *ms1Label = [[UILabel alloc] initWithFrame:CGRectMake(10,0, 150, 20)];
    ms1Label.textAlignment = 0;
    ms1Label.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
    ms1Label.textColor = [UIColor blackColor];
    [labelView addSubview:ms1Label];
    NSString *aString = [NSString stringWithFormat:@"%@",[[killArray objectAtIndex:selectInt] objectForKey:@"BeginDate"]];
    if (aString.length >16) {
        aString = [aString substringWithRange:NSMakeRange(11,5)];
    }
    NSMutableAttributedString *str =[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"秒杀%@开始",aString]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor]  range:NSMakeRange(2,5)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:labelSize-2] range:NSMakeRange(2,5)];
    ms1Label.attributedText = str;
    
    UIImageView *killImageView = [[UIImageView alloc] initWithFrame:CGRectMake(screenMySize.size.width-121,3, 333/3, 53/3)];
    [killImageView setImage:[UIImage imageNamed:@"killTime"]];
    [labelView addSubview:killImageView];
    

    [self gotoMSLabel];
        
    msLabel = [[UILabel alloc] initWithFrame:CGRectMake(screenMySize.size.width-85,2, 75, 20)];
    msLabel.textAlignment = 0;
    msLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
    msLabel.textColor = [UIColor whiteColor];
    [labelView addSubview:msLabel];
    [self msLabelTime];
        
    if (KillTimer != nil) {
        [KillTimer invalidate];
        KillTimer = nil;
    }
    KillTimer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(KillTimer:) userInfo:nil repeats:YES];
  
}

-(void)gotoMSLabel
{
    NSMutableDictionary *dictionary = [killArray objectAtIndex:0];
    NSString *timeString = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"BeginCountdown"]];
    NSArray *controls = [timeString componentsSeparatedByString:@":"];
    if (controls.count>3)
    {
        for (int i = 0; i <controls.count; i++) {
            if (i == 0)
                dayInt = [[controls objectAtIndex:i] intValue];
            else if (i == 1)
                hourInt = [[controls objectAtIndex:i] intValue];
            else if (i == 2)
                minuteInt = [[controls objectAtIndex:i] intValue];
            else if (i == 3)
                secondInt = [[controls objectAtIndex:i] intValue];
        }
    }
    else
    {
        for (int i = 0; i <controls.count; i++) {
            dayInt = 0;
            if (i == 0)
                hourInt = [[controls objectAtIndex:i] intValue];
            else if (i == 1)
                minuteInt = [[controls objectAtIndex:i] intValue];
            else if (i == 2)
                secondInt = [[controls objectAtIndex:i] intValue];
        }
    }
}

-(void)KillTimer:(NSTimer *)theTimer
{
    secondInt--;
    if (secondInt == 0 && (dayInt != 0 || hourInt !=0||minuteInt!= 0 ))
    {
        minuteInt--;
        secondInt = 59;
    }
    if (minuteInt == 0 &&(dayInt != 0 || hourInt !=0 ))
    {
        hourInt --;
        minuteInt = 59;
    }
    if (hourInt == 0 && dayInt != 0)
    {
        dayInt --;
        hourInt = 59;
    }
    [self msLabelTime];
    
    if (dayInt == 0 && hourInt == 0 && minuteInt == 0 && secondInt == 0 ) {
        
        msLabel.text = [NSString stringWithFormat:@"00   00    00"];
        [theTimer invalidate];
        theTimer = nil;
    }
}

-(void)msLabelTime
{
    NSString *h = [NSString stringWithFormat:@"%d",hourInt+dayInt*24];
    NSString *m = [NSString stringWithFormat:@"%d",minuteInt];
    NSString *s = [NSString stringWithFormat:@"%d",secondInt];
    if (hourInt < 10) {
        h = [NSString stringWithFormat:@"0%d",hourInt];
    }
    if (minuteInt < 10) {
        m = [NSString stringWithFormat:@"0%d",minuteInt];
    }
    if (secondInt < 10) {
        s = [NSString stringWithFormat:@"0%d",secondInt];
    }
    msLabel.text = [NSString stringWithFormat:@"%@   %@    %@",h,m,s];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[allArray objectForKey:[NSString stringWithFormat:@"%d",selectInt]] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return getableH;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"killList";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        aTableView.showsVerticalScrollIndicator = NO;
    }
    cell.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [[allArray objectForKey:[NSString stringWithFormat:@"%d",selectInt]] objectAtIndex:indexPath.row];
    
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10,10, getableH-20,getableH-20)];
    [bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"FullSizeImageUrl"]]]];
    bgImageView.contentMode =  UIViewContentModeScaleAspectFit;
    bgImageView.backgroundColor  = [UIColor whiteColor];
    [cell.contentView addSubview:bgImageView];

    
    [cell.contentView addSubview:[self setFrame:CGRectMake(getableH, 10, screenMySize.size.width-getableH-10, getableH-50) setTitle:[dic objectForKey:@"Name"]setColor:YES] ];
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(getableH, getableH-30, screenMySize.size.width-getableH-10, 20) setTitle:[[dic objectForKey:@"ProductPrice"]objectForKey:@"Price"] setColor:NO]];
    return cell;
}

-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setColor:(BOOL)black
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize];
    if (black)
        titleLabel.textColor = [UIColor blackColor];
    else
        titleLabel.textColor = [UIColor redColor];
    
    return titleLabel;
}

- (void)tableView:(UITableView *)table1View didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [[allArray objectForKey:[NSString stringWithFormat:@"%d",selectInt]] objectAtIndex:indexPath.row];
    
    GoodsDetailsViewController *details = [[GoodsDetailsViewController alloc] init];
    details.productId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Id"]];
    details.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:details animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
